import { EntityManager, MikroORM } from "@mikro-orm/mysql";
import { InjectEntityManager, InjectMikroORM } from "@mikro-orm/nestjs";
import { Body, Controller, Get, Inject, Post, Req, Res } from "@nestjs/common";
import { ApiTags } from "@nestjs/swagger";
import { PayService } from "../service/pay.service";
import Request from "node-easywechat/dist/Core/Http/Request";
import { Response } from "express";

@ApiTags('(站点) 账户')
@Controller('wxpay/callback')
export class WxpayCallbackController {
    constructor(
        @InjectMikroORM('zp')
        private readonly orm : MikroORM,
        @InjectEntityManager('zp')
        private readonly em : EntityManager,
        @Inject(PayService) 
        private readonly payService : PayService
    ){}

    @Get('order')
    async order(@Res() res : Response){
        // const result = await this.payService.payClient.order.unify({
        //     // appid: config.appid, // 小程序id  - EasyWechat 不用填
        //     // mch_id: config.mch_id, // 商户id   - EasyWechat 不用填
        //     // nonce_str: service.wx.randomStr(), // 自定义生成随机字符方法 - EasyWechat 不用填
        //     // sign_type: "MD5", // 加密类型 - EasyWechat 不用填
        //     // sign - EasyWechat 不用填
  
        //     body : '腾讯充值中心-QQ会员充值', // 商品简单描述，有格式要求
        //     out_trade_no: '20150806125346', // 订单号
        //     total_fee : 1, // 单位：分
        //     //spbill_create_ip: '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址, 服务器ip
        //     notify_url: "https://www.apesk.net/api/common/wxpay/callback/notify", // 支付成功通知地址// 支付结果通知网址，如果不设置则会使用配置里的默认地址
        //     trade_type: "JSAPI", // 支付方式（小程序支付选JSAPI）// 请对应换成你的支付方式对应的值类型
        //     openid: 'ogCCq5UfBCHxriyn99dOYjD95v9A', // 用户openid，步骤0保存的数据
        //   });
 
        //   return JsonApiResponse.new(result)
        
        res.header("Content-Type", "text/xml");
        return res.status(200).send('<xml><return_code>SUCCESS</return_code><return_msg/></xml>');
        // return 'OK';
    }


    @Post('notify2')
    notify2(@Req() request : Request ,@Body() formData)
    {
        this.payService.payClient.request = new Request(request as any) as any;

        const result = this.payService.payClient.handlePaidNotify((message, fail)=>{
            if(true)
            {
                console.log('服务器回调成功.')
            }else{
                fail('Order not exists.');
            }
        })

        return result
    }

    @Post('notify')
    async notify(@Req() request : Request ,@Body() formData,@Res() res : Response)
    {
        this.payService.payClient.request = new Request(request as any) as any;

        const result = await this.payService.payClient.handlePaidNotify((message, fail)=>{
            if(true)
            {
                console.log(message)
                console.log('服务器回调成功.')
                return true
            }else{
                fail('Order not exists.');
            }
        })

        // console.log(result)
        console.log(result.getContent().toString())

        res.header("Content-Type", "text/xml");
        return res.status(result.getStatusCode()).send(result.getContent().toString());
    }
}